import pymysql
import logging

# 配置日志（如有需要可调整配置）
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def insert_items_to_db(items):
    print(items,"items..items")
    # 请根据你的实际数据库配置修改下面参数
    connection = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='pear2008',
        database='chinese_dictionary',
        charset='utf8mb4'
    )
    try:
        with connection.cursor() as cursor:
            sql = """
            INSERT INTO chinese_words (phrase, pinyin, meaning, example_sentence)
            VALUES (%s, %s, %s, %s)
            """
            for item in items:
                phrase = item.get("phrase", "")
                pinyin = item.get("pinyin", "")
                meaning = item.get("meanings", "")
                sentence = item.get("sentence", "")
                cursor.execute(sql, (phrase, pinyin, meaning, sentence))
        connection.commit()
        logger.info("所有数据已成功插入数据库")
    except Exception as e:
        logger.error(f"数据库插入失败: {str(e)}")
        connection.rollback()
    finally:
        connection.close()

if __name__ == "__main__":
    # 假设 items 是你从 index.py 中收集的列表
    from index import items
    insert_items_to_db(items)